import model from '@backend/model'
import { DataSource } from 'typeorm'
import { isObject, clone, isNumber, isString } from 'lodash'
import { get_messages_list } from './message'
// @LINKS: chat Model => chat对象字段
const KeysAlias: KeyTans = {
    id: 'id',
    title: 'title',
    code: 'code',
    deltail: 'deltail',
    tokens: 'tokens',
    message: 'message',
    model: 'model',
    time: 'time'
}
// for plugin data return keys
const DataKeys: string[] =  ["id", "title", "code", "deltail", "tokens", "message", "model", "time"]
//@LINKS: chat Model => 模型Model类定义
class Chat{
    private id: number | null = null;
    private code: string = null;
    private _data: ChatData | null = null;
    private meta: object | null = null;
    private _M: DataSource =null

    constructor( idOrCode: number | string | NewSimpleParam ){
        if( isObject(idOrCode) ){
            this.id = idOrCode.id
        }else if( isNumber(idOrCode) ){
            this.id = idOrCode;
        }else if( isString(idOrCode) ){
            this.code = idOrCode;
        }
        this.getData()
    }

    private async getM(): Promise<DataSource>{
        if(!this._M){
            const { Chat: m } = await model('Chat'); 
            this._M = m
        }
        return this._M
    }

    //@LINKS: chat Model => 获取chat 数据
    async getData(): Promise<ChatData>{
        if( !this._data ){
            let re: {[key: string] : any} = null
            const  _chat = await this.getM();
            const d = await _chat.find({
                select: DataKeys,
                where:[{ id: this.id }, { code: this.code }]
            })

            if( d[0]){
                re = re || {}
                for(let key in d[0]){
                    if( KeysAlias[key] ){
                        re[ KeysAlias[key] ] = d[0][key]
                    }else{
                        re[key] = d[0][key]
                    }
                }
            }
            this._data = JSON.parse(JSON.stringify(re))
            this.id = this._data.id
            this.code = this._data.code
        }
        return this._data
    }
    // @LINKS: chat Model => 获取指定chatid的 list
    // return messages list
    async getMessageList() : Promise< Record<string, any>[] > {
        const re = await get_messages_list({
            where: {
                chat_id: this.id
            }
        })
        return re
    }
}

export async function get_chat( p: number | string | NewSimpleParam  ): Promise<Chat> {
    return Promise.resolve( new Chat( p ))
}

async function get_chats( where: object | undefined = {}): Promise< Array<Chat> > {
    const chats: Array<Chat> = []
    const { Chat: _chat }= await model('Chat')
    where = Object.assign({order: {
            id: "ASC",
        }}, where )
    const list = await _chat.find( where )
    for(const p of list){
        chats.push( await get_chat(p) )
    }
    return chats
}

export async function get_chat_data_list( where: object | undefined = {} ): Promise< ChatData[] > {
    const re:ChatData[] = []
    const chats = await get_chats(where)

    for( const p of chats){
        re.push( await p.getData() )
    }
    return re;
}